package com.fi.common.file;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.FileUtils;

import com.fi.common.exception.ExceptionUtils;
import com.fi.common.log.FiLog;



public class FileTool {
	/**
     * 删除单个文件
     * @param   filePath    被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
   public static boolean deleteFile(String filePath) {
	    File file = new File(filePath);
	        if (file.isFile() && file.exists()) {
	        return file.delete();
	        }
	        return false;
	}
	public static boolean Delete(String filePath) {
	    File file = new File(filePath);
	        if (!file.exists()) {
	            return false;
	        } else {
	            if (file.isFile()) {
	            // 为文件时调用删除文件方法
	                return deleteFile(filePath);
	            } else {
	            // 为目录时调用删除目录方法
	                return deleteDirectory(filePath);
	            }
	        }
	    }
	/**
     * 删除文件夹以及目录下的文件
     * @param   filePath 被删除目录的文件路径
     * @return  目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String filePath) {
    	boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
            //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } else {
            //删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前空目录
        return dirFile.delete();
    }
	/**
	 * http下载文件到dir本地
	 * */
    public static File downloadFromUrl(String url,String filepath) {  
    	File f = null;
        try {  
            URL httpurl = new URL(url);  
            f = new File(filepath);  
            FileUtils.copyURLToFile(httpurl, f);
            
        } catch (Exception e) {  
            e.printStackTrace();  
            return f;  
        }   
        return f;  
    }  
    /**
     * 通过url的字符串规则取出文件名
     * */
    private static String getFileNameFromUrl(String url){  
        String name = new Long(System.currentTimeMillis()).toString() + ".X";  
        int index = url.lastIndexOf("/");  
        if(index > 0){  
            name = url.substring(index + 1);  
            if(name.trim().length()>0){  
                return name;  
            }  
        }  
        return name;  
    }  
	
	/**
	 * 通过读取/proc/version得到KernelVersion
	 * 
	 * 
	 * @param context
	 * @return
	 */
	public static String getKernelVersion() {  
		String kernelVersion = "";  
		InputStream inputStream = null;  
		try {  
			inputStream = new FileInputStream("/proc/version");  
		} catch (FileNotFoundException e) {  
			ExceptionUtils.Log(e);
			return kernelVersion;  
		}  
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 8 * 1024);  
		String info = "";  
		String line = "";  
		try {  
			while ((line = bufferedReader.readLine()) != null) {  
				info += line;  
			}  
		} catch (IOException e) {  
			ExceptionUtils.Log(e);
		} finally {  
			try {  
				bufferedReader.close();  
				inputStream.close();  
			} catch (IOException e) {  
				ExceptionUtils.Log(e);
			}  
		}  

		try {  
			if (info != "") {  
				final String keyword = "version ";  
				int index = info.indexOf(keyword);  
				line = info.substring(index + keyword.length());  
				index = line.indexOf(" ");  
				kernelVersion = line.substring(0, index);  
			}  
		} catch (IndexOutOfBoundsException e) {  
			ExceptionUtils.Log(e);
		}  

		return kernelVersion;  
	} 
	
	
	  public static void copyFile(String srcPath, String dstPath) {   
	       try {   
	           int bytesum = 0;   
	           int byteread = 0;   
	           File oldfile = new File(srcPath);   
	           if (oldfile.exists()) { //文件不存在时   
	               InputStream inStream = new FileInputStream(srcPath); //读入原文件   
	               FileOutputStream fs = new FileOutputStream(dstPath);   
	               byte[] buffer = new byte[1444];   
	               int length;   
	               while ( (byteread = inStream.read(buffer)) != -1) {   
	                   bytesum += byteread; //字节数 文件大小   
	                   fs.write(buffer, 0, byteread);   
	               }
	               inStream.close();   
	           }else{
	        	   throw new Exception(String.format("copy the file %s  is not exists", srcPath));
	           }
	       }   
	       catch (Exception e) {   
	           //FiLog.appLogE("FiDebugInfo","copy a single file error : "+e.getMessage());   
	           ExceptionUtils.Log(e);
	  
	       }   
	   }   
	
	
	
	/**  
     * 
     * @param oldPath String  
     * @param newPath String  
     * @return boolean  
     */   
   public static void copyFolder(String oldPath, String newPath) {   
  
       try {   
           (new File(newPath)).mkdirs(); //
           File oldFile=new File(oldPath);
           String[] file=oldFile.list();
           File temp=null;   
           for (int i = 0; i < file.length; i++) {   
               if(oldPath.endsWith(File.separator)){   
                   temp=new File(oldPath+file[i]);   
               }   
               else{   
                   temp=new File(oldPath+File.separator+file[i]);   
               }   
  
               if(temp.isFile()){   
                   FileInputStream input = new FileInputStream(temp);   
                   FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());   
                   byte[] b = new byte[1024 * 5];   
                   int len;   
                   while ( (len = input.read(b)) != -1) {   
                       output.write(b, 0, len);   
                   }   
                   output.flush();   
                   output.close();   
                   input.close();   
               }   
               if(temp.isDirectory()){//
                   copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);   
               }   
           }   
       }   
       catch (Exception e) {   
           ExceptionUtils.Log(e);
       }   
  
   }  
	
	/**
	 * 写文件
	 * @param path
	 * @param inputStream
	 * @throws IOException
	 */
	public static  void writeFile(String path, InputStream inputStream)
				throws IOException {
			FileOutputStream fout = new FileOutputStream(path);
			int len = 0;
			byte[] data = new byte[10240];
			while (true) {
				len = inputStream.read(data);
				if (len <= 0)
					break;
				fout.write(data, 0, len);
			}
			fout.close();
			inputStream.close();
	}
	
	/**
	 * 向文件写入
	 * @param path
	 * @param inputStream
	 * @throws IOException
	 */
	public static  void writeFile(String path, String conent,boolean append){
		BufferedWriter out = null;
		FileOutputStream fileOs=null;
		createFile(path);//先创建文件
		try {
			fileOs=new FileOutputStream(path, append);
			out = new BufferedWriter(new OutputStreamWriter(fileOs));
			out.write(conent+"\n");
		} catch (Exception e) {
			ExceptionUtils.Log(e);
		} finally {
			try {
				out.close();
				fileOs.close();
			} catch (IOException e) {
				ExceptionUtils.Log(e);
			}
		}
	}
	
	
	
	
	
	
	/**
	 * 新建文件.
	 * @param path 文件路径
	 * @throws Exception
	 */
	public static void createFile(String path) {
		if (path==null || path.equals("")) {
			return;
		}
		try {
			// 获得文件对象
			File f = new File(path);
			if (f.exists()) {
				return;
			}
			// 如果路径不存在,则创建
			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdirs();
			}
			f.createNewFile();
		} catch (Exception e) {
			FiLog.appLogE("FileTool","create a new file error" + path+e);
		}
	}
	
	
	
	
	
	
	
	public static  void writeFile(String path, String conent){
		writeFile(path,conent,true);
	}
	
	
	/**
	 * 璇诲彇txt鏂囦欢镄勫唴瀹?
	 * 
	 */
	public static String ReadTxtFile(String strFilePath)
    {
        String path = strFilePath;
        String content = ""; //鏂囦欢鍐呭瀛楃涓?
            //镓揿紑鏂囦欢
            File file = new File(path);
            //濡傛灉path鏄紶阃掕绷鏉ョ殑鍙傛暟锛屽彲浠ュ仛涓?涓潪鐩綍镄勫垽鏂?
            if (file.isDirectory())
            {
            	FiLog.appLogE("TestFile", "The File doesn't not exist.");
            }
            else
            {
                try {
                    InputStream instream = new FileInputStream(file); 
                    if (instream != null) 
                    {
                        InputStreamReader inputreader = new InputStreamReader(instream);
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line;
                        //鍒呜璇诲彇
                        while (( line = buffreader.readLine()) != null) {
                            content += line + "\n";
                        }                
                        instream.close();
                    }
                }
                catch (java.io.FileNotFoundException e) 
                {
                	FiLog.appLogE("TestFile", "The File doesn't not exist.");
                } 
                catch (IOException e) 
                {
                	FiLog.appLogE("TestFile", e.getMessage());
                }
            }
            return content;
    }

	
	/**
	 * 解压zip文件
	 * 
	 * @param unZipfileName  zip文件名
	 * @param mDestPath  	解压目标路径
	 */
	public static void unZip(String unZipfileName, String mDestPath) {
		if (!mDestPath.endsWith("/")) {
			mDestPath = mDestPath + "/";
		}
		FileOutputStream fileOut = null;
		ZipInputStream zipIn = null;
		ZipEntry zipEntry = null;
		File file = null;
		int readedBytes = 0; 
		byte buf[] = new byte[4096];
		try {
			zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)));
			while ((zipEntry = zipIn.getNextEntry()) != null) {
				file = new File(mDestPath + zipEntry.getName());
				if (zipEntry.isDirectory()) {
					file.mkdirs();
				} else {
					// 濡傛灉鎸囧畾鏂囦欢镄勭洰褰曚笉瀛桦湪,鍒椤垱寤轰箣.
					File parent = file.getParentFile();
					if (!parent.exists()) {
						parent.mkdirs();
					}
					fileOut = new FileOutputStream(file);
					while ((readedBytes = zipIn.read(buf)) > 0) {
						fileOut.write(buf, 0, readedBytes);
					}
					fileOut.close();
				}
				zipIn.closeEntry();
			}
		} catch (Exception e) {
			ExceptionUtils.Log(e);
		}
	}
	
}

